package com.ostrich.cloud.ostrichUserService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ostrich.cloud.common.result.PageResult;
import com.ostrich.cloud.common.result.Result;

import com.ostrich.cloud.ostrichPermission.client.PermissionClient;
import com.ostrich.cloud.ostrichPermission.client.param.AddUserParam;
import com.ostrich.cloud.ostrichUserService.common.CustomerResultCode;
import com.ostrich.cloud.ostrichUserService.common.RoleLevel;
import com.ostrich.cloud.ostrichUserService.common.exception.CusException;
import com.ostrich.cloud.ostrichUserService.common.stateEnum.CluStateEnum;
import com.ostrich.cloud.ostrichUserService.common.utils.Algorithm;
import com.ostrich.cloud.ostrichUserService.infra.mapper.CustomerMapper;
import com.ostrich.cloud.ostrichUserService.infra.mapper.UserParentMapper;
import com.ostrich.cloud.ostrichUserService.infra.model.Customer;
import com.ostrich.cloud.ostrichUserService.infra.model.UserParent;
import com.ostrich.cloud.ostrichUserService.service.CustomerService;
import com.ostrich.ostrichUserService.dto.CustomerDto;
import com.ostrich.ostrichUserService.param.CusPasswordParam;
import com.ostrich.ostrichUserService.param.LoginCusParam;
import com.ostrich.ostrichUserService.param.RegCustomerParam;
import com.ostrich.ostrichUserService.param.UpdateCusParam;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-10-26
 */
@Service
@Slf4j
@GlobalTransactional
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private PermissionClient permissionClient;

    @Resource
    private UserParentMapper userParentMapper;

    @Override

    public void Register(RegCustomerParam reg) {
        AddUserParam addUserParam = new AddUserParam();
        addUserParam.setUsername(reg.getUsername());
        /**
         * 密码进行加密
         */
        addUserParam.setPassword(Algorithm.md5(reg.getPassword()));
        addUserParam.setRoleId(RoleLevel.CUSTOMER);
        Result result = permissionClient.addUser(addUserParam);
        if (result.getCode()!=200){
            throw new CusException(CustomerResultCode.USERNAME_COPY_EXCEPTION);
        }
        Integer parentId = (Integer) result.getData();
        Customer customer = new Customer();
        customer.setParentId(parentId);
        customer.setCustomerMoney(BigDecimal.ZERO);
        customer.setPayPassword("000000");
        customer.setCreateTime(new Date());
        customer.setCustomerStatus(CluStateEnum.NORMAL.getCode());
        customer.setMobile(Long.parseLong(reg.getMobile()));

       customerMapper.insert(customer);
    }

    @Override
    public void updateCusMessage(Customer customer) {
        UpdateWrapper<Customer> customerUpdateWrapper = new UpdateWrapper<>();
        customerUpdateWrapper.eq("parent_id",customer.getParentId())
                .set(customer.getImage()!=null,"image",customer.getImage())
                .set(customer.getPayPassword()!=null,"pay_password",customer.getPayPassword())
                .set(customer.getBirthday()!=null,"birthday",customer.getBirthday())
                .set(customer.getMobile()!=null,"mobile",customer.getMobile());
         customerMapper.update(null,customerUpdateWrapper);
    }

    @Override
    public PageResult<CustomerDto> getAllCusMessage(Integer current, Integer size,String status) {
        PageResult<CustomerDto> pageResult = new PageResult<>();
        Page<CustomerDto> page = new Page<>();
        page.setCurrent(current).setSize(size);
        IPage<CustomerDto> customerIPage = customerMapper.getAllCusMessage(page, status);
        log.info("分页查询的结果{}",customerIPage);
        pageResult.setElements(customerIPage.getRecords());
        pageResult.setPage(customerIPage.getCurrent());
        pageResult.setPageSize(customerIPage.getSize());
        pageResult.setTotal(customerIPage.getTotal());
        pageResult.setTotalPage(customerIPage.getPages());


        return pageResult;
    }

    @Override
    public UserParent customerLogin(LoginCusParam lo) {
        QueryWrapper<UserParent> query = new QueryWrapper<>();
        query.eq("username",lo.getUsername())
                .eq("password",Algorithm.md5(lo.getPassword()));
        UserParent userParent = userParentMapper.selectOne(query);
        if (userParent==null){
            throw new CusException(CustomerResultCode.PASSWORD_EXCEPTION);
        }
        if(CluStateEnum.CANCEL.getCode().equals(userParent.getStatus())){
            throw new CusException(CustomerResultCode.CANCEL_EXCEPTION);
        }

        return userParent;
    }

    @Override
    public void updatePassword(CusPasswordParam cusPasswordParam) {
        UpdateWrapper<UserParent> parentUpdateWrapper = new UpdateWrapper<>();
        log.info("用户密码是{}",Algorithm.md5(cusPasswordParam.getPassword()));
        parentUpdateWrapper.eq("parent_id",cusPasswordParam.getParentId())
                .eq("password",Algorithm.md5(cusPasswordParam.getPassword()))
                .set("password",Algorithm.md5(cusPasswordParam.getNewPassword()));
        if(!(userParentMapper.update(null, parentUpdateWrapper) >0)){
            throw new CusException(CustomerResultCode.PASSWORD_EXCEPTION);
        };

    }

    @Override
    public void upCusStatus(Integer parentId,String status) {

        UpdateWrapper<UserParent> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("parent_id",parentId)
                .set("status",status);
        userParentMapper.update(null,updateWrapper);
        UpdateWrapper<Customer> updateCuWrapper = new UpdateWrapper<>();
        updateCuWrapper.eq("parent_id",parentId)
                .set("customer_status",status);
        customerMapper.update(null,updateCuWrapper);
    }

    /**
     * 充值
     * @param parentId
     * @param total_amount
     */
    @Override
    public void pay(Integer parentId, String total_amount) throws TransactionException {
            try {
                UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();

                Customer customer = customerMapper.selectOne(new QueryWrapper<Customer>().eq("parent_id", parentId));

                updateWrapper.eq("parent_id",parentId)
                        .set("customer_money",customer.getCustomerMoney().add(BigDecimal.valueOf(Long.parseLong(total_amount))));
                customerMapper.update(null,updateWrapper);
            }catch(Exception e){
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            }


    }

    @Override
    public void reduce(Integer parentId, BigDecimal price) throws TransactionException {
        try {
            UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("parent_id",parentId)
                    .set("customer_money",price);
            customerMapper.update(null,updateWrapper);
        }catch(Exception e){
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        }

    }
}
